package cn.jiaqiang.chatgpt.data.domain.openai.service.rule.impl.filter;


import cn.jiaqiang.chatgpt.data.domain.openai.annotation.LogicStrategy;
import cn.jiaqiang.chatgpt.data.domain.openai.model.aggregates.ChatProcessAggregate;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.MessageEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.RuleLogicEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.UserAccountEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.valobj.LogicCheckTypeVO;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.ILogicFilter;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.factory.DefaultLogicFactory;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description 敏感词过滤
 * @create 2023-09-16 17:39
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.SENSITIVE_WORD)
public class SensitiveWordFilter implements ILogicFilter<UserAccountEntity> {

    @Resource
    private SensitiveWordBs words;

    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcess, UserAccountEntity data)  {

        log.info("userId = {} 开始进行【敏感词拦截】", chatProcess.getUserId());
        ChatProcessAggregate newChatProcessAggregate = new ChatProcessAggregate();
        newChatProcessAggregate.setUserId(chatProcess.getUserId());

        newChatProcessAggregate.setModel(chatProcess.getModel());

        // 拿到过滤后的新的 message
        List<MessageEntity> newMessages = chatProcess.getMessages().stream()
                .map(message -> {
                    String content = message.getContent();
                    // 通过敏感词过滤器 SensitiveWordBs 对消息内容进行敏感词替换处理
                    String replace = words.replace(content);
                    return MessageEntity.builder()
                            .role(message.getRole())
                            .name(message.getName())
                            .content(replace)
                            .build();
                })
                .collect(Collectors.toList());

        newChatProcessAggregate.setMessages(newMessages);

        // 返回新的请求信息, 这个过滤器返回的一定是 LogicCheckTypeVO.SUCCESS
        log.info("userId = {}, 【敏感词拦截】结果: {}", chatProcess.getUserId(), LogicCheckTypeVO.SUCCESS.getInfo());
        return RuleLogicEntity
                .<ChatProcessAggregate>builder()
                .type(LogicCheckTypeVO.SUCCESS)
                .data(newChatProcessAggregate)
                .build();
    }

}
